package com.study.netty.server;

import com.study.netty.channel.BootNettyUdpSimpleChannelInboundHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BootNettyUdpServer {
    /**
     * 启动服务
     */
    public void bind(int port) {

        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            //UDP方式使用Bootstrap
            Bootstrap serverBootstrap = new Bootstrap();
            serverBootstrap = serverBootstrap.group(eventLoopGroup);
            serverBootstrap = serverBootstrap.channel(NioDatagramChannel.class);
            serverBootstrap = serverBootstrap.option(ChannelOption.SO_BROADCAST, true);
            //不需要太多其他的东西，直接这样就可以用
            serverBootstrap = serverBootstrap.handler(new BootNettyUdpSimpleChannelInboundHandler());
            log.info("netty udp start!");
            ChannelFuture f = serverBootstrap.bind(port).sync();
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            log.info("netty udp close!");
            eventLoopGroup.shutdownGracefully();
        }
    }
}
